<template>
  <el-dropdown :title="selectedTitle || title" trigger="click">
    <span class="el-dropdown-link">
      {{ selectedTitle || title }}
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="(item, index) in menuItems"
          :key="index"
          @click="handleClick(item)"
        >
          {{ item.label }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { ArrowDown } from '@element-plus/icons-vue'
import { ref } from 'vue'

const props = defineProps({
  title: {
    type: String,
    default: '下拉菜单'
  },
  menuItems: {
    type: Array,
    default: () => [
      { label: 'Action 1', value: 'action1' },
      { label: 'Action 2', value: 'action2' },
      { label: 'Action 3', value: 'action3' }
    ]
  },
  // 新增：是否跟随选择变化
  dynamicTitle: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['item-click'])

// 新增：选中的标题
const selectedTitle = ref(null)

const handleClick = (item) => {
  if (props.dynamicTitle) {
    selectedTitle.value = item.label
  }
  emit('item-click', item)
}

// 新增：提供重置标题的方法
const resetTitle = () => {
  selectedTitle.value = null
}

// 暴露方法给父组件
defineExpose({
  resetTitle
})
</script>
